package cn.yqm.modules.admin.service;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.yqm.common.UserModel;
import cn.yqm.common.YqmProperties;
import cn.yqm.common.YqmSessionUtils2;
import cn.yqm.common.enums.YqmStatusEnum;
import cn.yqm.common.exception.YqmException;
import cn.yqm.common.factory.LoginFactory;
import cn.yqm.dto.YqmSysUserDto;
import cn.yqm.entity.YqmSysDept;
import cn.yqm.entity.YqmSysUser;
import cn.yqm.entity.YqmSysUserPost;
import cn.yqm.entity.YqmSysUserRole;
import cn.yqm.req.YqmSysUserPostReq;
import cn.yqm.req.YqmSysUserReq;
import cn.yqm.req.YqmSysUserRoleReq;
import cn.yqm.service.IYqmSysDeptService;
import cn.yqm.service.IYqmSysUserPostService;
import cn.yqm.service.IYqmSysUserRoleService;
import cn.yqm.service.IYqmSysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户服务
 *
 * @author weiximei
 * @domain www.yqmshop.cn
 * @since 2023/8/4
 */
@AllArgsConstructor
@Service
public class UserService {

    private final IYqmSysUserService iYqmSysUserService;
    private final IYqmSysDeptService iYqmSysDeptService;
    private final YqmProperties yqmProperties;
    private final IYqmSysUserPostService iYqmSysUserPostService;
    private final IYqmSysUserRoleService iYqmSysUserRoleService;

    /**
     * 登录
     *
     * @param account
     * @param password
     * @param loginType
     * @return
     */
    public Object login(String account, String password, String loginType, Boolean remember) {
        return LoginFactory.getSingle(loginType).login(account, password, remember);
    }

    /**
     * 获取当前登录的用户信息
     *
     * @return
     */
    public YqmSysUserDto getLoginInfo() {
        YqmSysUserDto yqmSysUserDto = YqmSysUserDto.builder().build();

        UserModel userModel = YqmSessionUtils2.getSessionUser();
        YqmSysUser yqmSysUser = iYqmSysUserService.getById(Long.valueOf(userModel.getId()));

        BeanUtil.copyProperties(yqmSysUser, yqmSysUserDto);

        // TODO: 查询角色
        yqmSysUserDto.setRoles(Lists.newArrayList("admin"));

        return yqmSysUserDto;
    }


    /**
     * 分页查询
     *
     * @param req
     * @return
     */
    public IPage<YqmSysUserDto> page(YqmSysUserReq req) {

        if (Objects.nonNull(req.getDeptId())) {
            List<YqmSysDept> deptList = iYqmSysDeptService.getDeptChildren(req.getDeptId());
            List<Long> deptIdList = deptList.stream().map(YqmSysDept::getDeptId).collect(Collectors.toList());
            req.setDeptIdList(deptIdList);
        } else {
            if (StringUtils.isNotBlank(req.getDeptIdListStr())) {
                req.setDeptIdList(Lists.newArrayList(Objects.requireNonNull(StringUtils.split(req.getDeptIdListStr(), ","))).stream().map(Long::valueOf).toList());
            }
        }

        IPage<YqmSysUser> page = new Page<>(req.getPage(), req.getPageSize());
        IPage pageList = iYqmSysUserService.page(page, iYqmSysUserService.getQuery(req));
        pageList.setRecords(BeanUtil.copyToList(pageList.getRecords(), YqmSysUserDto.class));

        if (CollectionUtils.isNotEmpty(pageList.getRecords())) {
            List<YqmSysUserDto> dtoList = (List<YqmSysUserDto>) pageList.getRecords();
            dtoList.forEach(e -> {
                // 查询岗位
                List<YqmSysUserPost> yqmSysUserPosts = iYqmSysUserPostService.list(iYqmSysUserPostService.getQuery(YqmSysUserPostReq.builder().userId(e.getUserId()).build()));
                if (CollectionUtils.isNotEmpty(yqmSysUserPosts)) {
                    e.setPostIds(yqmSysUserPosts.stream().map(YqmSysUserPost::getPostId).collect(Collectors.toList()));
                }
                // 查询角色
                List<YqmSysUserRole> yqmSysUserRoles = iYqmSysUserRoleService.list(iYqmSysUserRoleService.getQuery(YqmSysUserRoleReq.builder().userId(e.getUserId()).build()));
                if (CollectionUtils.isNotEmpty(yqmSysUserPosts)) {
                    e.setRoleIds(yqmSysUserRoles.stream().map(YqmSysUserRole::getRoleId).collect(Collectors.toList()));
                }
            });

        }


        return pageList;
    }

    /**
     * 保存/或修改
     *
     * @param req
     * @return
     */
    public YqmSysUserDto save(YqmSysUserReq req) {
        YqmSysUser yqmSysUser = new YqmSysUser();
        if (Objects.nonNull(req.getUserId())) {
            yqmSysUser = iYqmSysUserService.getById(req.getUserId());
        }

        if (StringUtils.isNotBlank(req.getPassword())) {
            String yPassword = SaSecureUtil.aesEncrypt(yqmProperties.getCipherKey(), req.getPassword());
            req.setPassword(yPassword);
        }

        BeanUtil.copyProperties(req, yqmSysUser);
        iYqmSysUserService.saveOrUpdate(yqmSysUser);

        Long userId = yqmSysUser.getUserId();

        QueryWrapper<YqmSysUserPost> deletePostQuery = new QueryWrapper<>();
        deletePostQuery.eq("user_id", userId);
        iYqmSysUserPostService.remove(deletePostQuery);

        QueryWrapper<YqmSysUserRole> deleteRoleQuery = new QueryWrapper<>();
        deleteRoleQuery.eq("user_id", userId);
        iYqmSysUserRoleService.remove(deleteRoleQuery);

        if (CollectionUtils.isNotEmpty(req.getPostIds())) {
            List<YqmSysUserPost> yqmSysUserPosts = req.getPostIds().stream().map(e -> YqmSysUserPost.builder().postId(e).userId(userId).build()).collect(Collectors.toList());
            iYqmSysUserPostService.saveBatch(yqmSysUserPosts);
        }

        if (CollectionUtils.isNotEmpty(req.getRoleIds())) {
            List<YqmSysUserRole> yqmSysUserRoles = req.getRoleIds().stream().map(e -> YqmSysUserRole.builder().roleId(e).userId(userId).build()).collect(Collectors.toList());
            iYqmSysUserRoleService.saveBatch(yqmSysUserRoles);
        }

        YqmSysUserDto sysRoleDto = YqmSysUserDto.builder().build();
        BeanUtil.copyProperties(yqmSysUser, sysRoleDto);
        return sysRoleDto;
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    public YqmSysUserDto getById(String id) {
        YqmSysUser yqmSysUser = new YqmSysUser();
        if (StringUtils.isNotBlank(id)) {
            yqmSysUser = iYqmSysUserService.getById(id);
        }

        YqmSysUserDto sysRoleDto = YqmSysUserDto.builder().build();
        BeanUtil.copyProperties(yqmSysUser, sysRoleDto);

        // 查询岗位
        List<YqmSysUserPost> yqmSysUserPosts = iYqmSysUserPostService.list(iYqmSysUserPostService.getQuery(YqmSysUserPostReq.builder().userId(sysRoleDto.getUserId()).build()));
        if (CollectionUtils.isNotEmpty(yqmSysUserPosts)) {
            sysRoleDto.setPostIds(yqmSysUserPosts.stream().map(YqmSysUserPost::getPostId).collect(Collectors.toList()));
        }
        return sysRoleDto;
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    public boolean delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new YqmException("数据不存在！请检查");
        }
        return iYqmSysUserService.removeByIds(ids);
    }

    /**
     * 启用/停用
     *
     * @param req
     * @return
     */
    public boolean enable(YqmSysUserReq req) {

        if (Objects.nonNull(YqmStatusEnum.getValue(req.getStatus()))) {
            YqmSysUser yqmSysUser = iYqmSysUserService.getById(req.getUserId());
            yqmSysUser.setStatus(req.getStatus());

            BeanUtil.copyProperties(yqmSysUser, req);
            this.save(req);
        }

        return false;
    }

    /**
     * 删除
     *
     * @return
     */
    public boolean deleteById(String id) {
        if (StringUtils.isBlank(id)) {
            throw new YqmException("数据不存在！请检查");
        }
        return iYqmSysUserService.removeById(Long.valueOf(id));
    }

}
